;
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/01/12
 * Time: 13:10
 * @link http://www.lmterp.cn
 */
layui.define(['layer', 'form', 'element', 'laydate', 'dropdown'], function (exports) {
    var layer = layui.layer,
        element = layui.element,
        table = layui.table,
        laydate = layui.laydate,
        form = layui.form,
        $ = layui.$;

    var longli = {
        // 数组去重复
        uniqueArray: function(array)
        {
            var ret = [];
            for(var i in array)
            {
                if($.inArray(array[i], ret) < 0) ret.push(array[i]);
            }
            return ret;
        }
        // post 提交 json
        , postJson: function(url, json, fn)
        {
            $.ajax({
                type: "post",
                url: url,
                dataType : "json",
                data: typeof json === "string" ? json : JSON.stringify(json),
                success: function(response)
                {
                    if(typeof fn === "function") fn(response);
                }

            }).fail(function (xhr) {
                layer.msg('服务器异常，请稍后重试~', {icon: 5});
                layer.closeAll('loading');
            });
        }
        // 复制字符串
        , copyText: function(text)
        {
            if(!text) return;
            if(text instanceof $) text = text.text();
            if($("#__copy-textarea__").length < 1) $("<textarea style='width: 0px;height: 0px;' id='__copy-textarea__'/>").appendTo("body");
            $("#__copy-textarea__").val($.trim(text)); // 修改文本框的内容
            $("#__copy-textarea__").get(0).select(); // 选中文本
            document.execCommand("copy"); // 执行浏览器复制命令
            layer.msg("复制成功", {icon: 6, time: 2000});
        }
        // 使用当前时间添加天数
        , addDay: function(day)
        {
            day = day || 0;
            var d = new Date((new Date()).getTime() + 86400000 * day);
            return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
        }
        // 播放 MP3
        , playMP3: function(name)
        {
            if(!name) return;
            if($("#__mp3-play__").length < 1) $("<audio style='display: none;' id='__mp3-play__' autoplay/>").appendTo("body");
            $("#__mp3-play__").attr("src", "/static/mp3/" + name + ".mp3");
        }
        ,
        // 渲染下拦菜单
        renderDropdown: function(options)
        {
            options = options || {};
            $(".dropdown-operation").each(function()
            {
                var $this = $(this)
                    , data = []
                    , assign = {}
                    , temp;
                if((temp = $this.data("assign")) && $.type(temp) == "object") assign = temp;
                $this.parent().find(".dropdown-template .layui-btn").each(function()
                {
                    var $this = $(this)
                        , s = {
                            title: "操作",
                            templet: $this.wrap("<div/>").parent().html().trim()
                        };
                    if($this.data("url"))
                    {
                        s["href"] = $this.data("url");
                        s["target"] = $this.attr("target") ? $this.attr("target") : "_self";
                    }
                    $.extend(s, assign);
                    data.push(s);
                });
                layui.dropdown.render({
                    elem: this
                    , delay: 500000
                    , data: data
                    , trigger: options.trigger || 'click'
                });
            });
        }
    };

    // 复制文本
    $(document).on("click", ".copy-text", function()
    {
        var $this = $(this),
            text = $this.is("input") ? $this.val() : $this.text();
        longli.copyText($.trim(text));
    });

    // 全选
    $(document).on("click", ".checked-all", function()
    {
        var $this = $(this), target = $this.attr("target");
        if(!target)return false;
        $("."+target).prop("checked", $this.prop("checked"));
    });

    //导航菜单
    $('.aside li>a').click(function (e) {
        e.stopPropagation();
        var next = $(this).next('dl');
        if (!$(this).next('dl').length) {
            return;
        }
        if (next.css('display') == 'none') {
            $(this).addClass('active');
            next.slideDown(500);
        } else {
            next.slideUp(500);
            $(this).removeClass('active');
        }
        return false;
    });
    //侧边隐藏
    $('.ajax-flexible').click(function () {
        var href = $(this).attr('href');
        var dom = $('.layui-layout-admin');
        var menu = dom.attr('layui-layout') == 'closed' ? 'open' : 'closed';
        dom.attr('layui-layout', menu);
        $.get(href, 'menu=' + menu);
        return false;
    });

    //表格初始化
    $.fn.getList = function (callback, history) {
        var that = this;
        var url = that.data('url');
        if (!url) return false;
        var param = that.find('form:first').serialize();
        var page = that.data('page') || 1;
        if (history) {
            page = 1;
        }
        param = 'page=' + page + '&' + param;
        layer.load(0, {shade: false});
        $.ajax({
                url: url,
                type: 'POST',
                dataType: 'html',
                data: param,
            })
            .done(function (html) {
                layer.closeAll('loading');
                that.find('.data').empty().html(html);
                form.render();
                longli.renderDropdown();
                that.data('page', page);
            })
            .fail(function (xhr) {
                layer.msg('服务器异常，请稍后重试~', {icon: 5});
                layer.closeAll('loading');
                console.log(xhr.responseText);
                that.find('.data').empty().html('<p><i class="fa fa-warning"></i> 服务器异常，请稍后再试~</p>');
            })
            .always(function () {
                if (typeof callback === 'function') {
                    callback();
                }
            });
    };
    $('.data-list').each(function()
    {
        $(this).getList({}, true);
    });

    //点击搜索
    $(document).on('click', '.search', function (event) {
        event.preventDefault();
        $(this).closest('.data-list').data('page', 1);
        var that = $(this);
        that.html('<i class="layui-icon layui-anim layui-anim-rotate layui-anim-loop layui-icon-loading"></i>');
        that.closest('.data-list').getList(function () {
            that.html('<i class="layui-icon layui-icon-search"></i>');
        });

    });
    //自动搜索
    form.on('select(data-list)', function (data) {
        $(data.elem).closest('.data-list').getList();
    });

    //分页
    $(document).on('click', '.layui-laypage-page>a', function () {
        var page = $(this).attr('lay-page');
        $(this).closest('.data-list').data('page', page).getList();
        return false;
    });
    //分页跳转
    $(document).on('click', '.layui-laypage-page .layui-laypage-btn', function () {
        var dom = $(this).closest('.data-list');
        var input = $(this).prev('input');
        var page = input.val();
        if (!page) {
            layer.msg('请输入页码');
            return false;
        }
        if (parseInt(page) > parseInt(input.attr('max')) || parseInt(page) < parseInt(input.attr('min'))) {
            layer.msg('页码范围为' + input.attr('min') + '~' + input.attr('max'));
            return false;
        }
        $(this).closest('.data-list').data('page', page).getList(href);
        return false;
    });

    //快速排序
    $(document).on('change', '.data-list table .layui-input', function(event)
    {
        event.preventDefault();
        var self = $(this);
        var url = self.attr('href') || self.data('url');
        if(self.val() != self.attr('data-val'))
        {
            $.post(url, self.serialize(), function(res)
            {
                if(res.code == 1)
                {
                    layer.msg(res.msg);
                    self.closest('.data-list').getList();
                }
                else
                {
                    self.attr('data-val', self.val());
                }
            });
        }
    });

    /**
     * 异步获取表单
     * 异步提交表单
     * 表单验证
     */
    $(document).on('click', '.ajax-form', function (event) {
        event.preventDefault();
        var self = $(this);
        if (self.attr('disabled')) return false;
        var url = self.attr('href') || self.data('url')
            , width = self.attr('width-form') || '30%'
            , height = self.attr('height-form') || '50%';
        if (!url) return;
        layer.load(0, {shade: false});
        $.get(url).done(function(html)
        {
            layer.closeAll('loading');
            if ($.type(html) === 'object')
            {
                layer.msg(html.msg, {icon: html.code == 1 ? 6 : 5});
                return false;
            }
            parent.layer.open({
                type: 1,
                title: self.attr('title'),
                content: html,
                scrollbar: false,
                area: [width, height],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    if ($(layero).find('.layui-layer-btn0').attr('disabled')) {
                        return false;
                    }
                    $(layero).find('.layui-layer-btn0').attr('disabled', 'disabled');
                    var _form = $(layero).find('form:first');
                    if(!_form.attr('action'))
                    {
                        layer.close(index);
                        return false;
                    }
                    _form.click();
                    layer.load(0, {shade: false});
                    $.post(_form.attr('action'), _form.serialize()).done(function(res)
                    {
                        layer.closeAll('loading');
                        if(res.code == 1)
                        {
                            if($('.data-list').length == 0)
                            {
                                location.reload();
                                return false;
                            }
                            self.closest('.data-list').getList();
                            layer.msg(res.msg, {
                                time: 1000,
                                icon: 6
                            }, function () {
                                layer.close(index);
                            });
                        }else
                        {
                            var str = res.msg || '服务器异常';
                            layer.msg(str, {
                                time: 2000,
                                icon: 5
                            });
                            $(layero).find('.layui-layer-btn0').removeAttr('disabled');
                        }
                    }).error(function(xhr)
                    {
                        layer.msg('服务器异常，请稍后重试~', {icon: 5});
                        layer.closeAll('loading');
                        $(layero).find('.layui-layer-btn0').removeAttr('disabled')
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                },
                success: function(layero, index){
                    $(layero).find('.layui-layer-btn0').attr("lay-submit", "");
                    form.render();
                    if(self.attr('close'))
                    {
                        setTimeout(function(){layer.close(index);}, 2000);
                    }
                },
                end: function()
                {
                    var $input = $("#" + self.attr("auto-focus") + ":input");
                    if($input.length > 0) $input.focus();
                }
            }, 'html');
        }).error(function(xhr)
        {
            layer.msg('服务器异常，请稍后重试~', {icon: 5});
            layer.closeAll('loading');
        });
        return false;
    });

    /**
     * 异步url请求
     * 用户简单操作，如删除
     */
    $(document).on('click', '.ajax-get', function (event) {
        event.preventDefault();
        var self = $(this);
        var url = self.attr('href') || self.data('url');
        var title = self.attr('title') || '执行该操作';
        if (!url) return false;

        if (self.attr('confirm')) {
            layer.confirm('您确定要 <span style="color:#f56954">' + title + '</span> 吗？', function (index) {
                layer.load(0, {shade: false});
                $.get(url, function (res) {
                    layer.closeAll('loading');
                    var icon = res.code == 1 ? 6 : 5;
                    layer.msg(res.msg, {icon: icon, time: 1500});
                    self.closest('.data-list').getList();
                }).error(function(xhr)
                {
                    layer.msg('服务器异常，请稍后重试~', {icon: 5});
                    layer.closeAll('loading');
                });
            });

        } else {
            layer.load(0, {shade: false});
            $.get(url).done(function(res)
            {
                layer.closeAll('loading');
                var message = self.attr('msg') || 1;
                var icon = res.code == 1 ? 6 : 5;
                if (res.code == 0 || message == 1) {
                    layer.msg(res.msg, {icon: icon, time: 1500});
                }
                self.closest('.data-list').getList();
            }).error(function(xhr)
            {
                layer.msg('服务器异常，请稍后重试~', {icon: 5});
                layer.closeAll('loading');
            });
        }
        return false;
    });

    // 删除表格 tr 一行
    $(document).on("click", ".remove-tr-btn", function()
    {
        $(this).parentsUntil('tr').parent().remove();
    });

    //监听table swtich操作
    form.on('switch(table-status)', function (obj) {
        var self = $(obj.elem);
        var table = self.closest('.data-table').data('id');
        $.ajax({
                url: self.data('href'),
                type: 'post',
                dataType: 'json'
            })
            .done(function (data) {
                if (data.code != 1) {
                    layer.msg(data.msg);
                    $(table).reload();
                }
            })
            .fail(function (xhr) {
                layer.msg('服务器异常，请稍后重试~', {icon: 5});
                layer.closeAll('loading');
                console.log(xhr.responseText);
                $(table).reload();
            });
    });

    /**
     *监听提普通交
     */
    form.on('submit(layform)', function (data) {
        var self = $(data.elem);
        if (self.attr('disabled')) {
            return false;
        }
        self.attr('disabled', 'disabled');
        $.ajax({
                url: data.form.action || '',
                type: 'POST',
                dataType: 'json',
                data: data.field
            })
            .done(function (res) {
                if (res.code == 1) {
                    layer.msg(res.msg, {
                        time: 1000,
                        icon: 6
                    }, function () {
                        if (res.url) window.location.href = res.url;
                    });
                } else {
                    layer.msg(res.msg, {
                        time: 1500,
                        icon: 5
                    });
                }
            })
            .fail(function () {
                layer.msg('服务器异常，请稍后重试~', {icon: 5});
                layer.closeAll('loading');
            })
            .always(function () {
                self.removeAttr('disabled');
            });
        return false;
    });

    // 时间范围填充
    $('.laydate-range').each(function()
    {
        laydate.render({
            elem: this,
            type: 'date',
            trigger: 'click',
            range: '~'
        });
    });

    // 填充未来时间
    $(".laydate-date-future").each(function()
    {
        laydate.render({
            elem: this
            ,min: 0
        });
    });

    // 刷新
    $('#refresh').click(function () {
        var self = $(this);
        var length = $('.data-list').length;
        if (self.attr('disabled') || !length) {
            return false;
        }
        self.attr('disabled', 'disabled');
        self.find('i').addClass('layui-anim').addClass('layui-anim-rotate').addClass('layui-anim-loop');
        $('.data-list').each(function (index, el) {
            $(this).getList(function () {
                if (index + 1 >= length) {
                    self.find('i').removeClass('layui-anim').removeClass('layui-anim-rotate').removeClass('layui-anim-loop');
                    self.removeAttr('disabled')
                }
            });
        });
    });

    //自定义验证规则
    var validate = {
        // 检测空字符串
        checkEmptyString: function(value)
        {
            if(value.trim().length > 0) return "字符串不为空"
        }
        // 检测输入的值是否为数字
        ,checkEmptyOrNumber: function (value)
        {
            value = value.trim();
            if(value.length > 0 && isNaN(value)) return "只能输入数字";
        }
        // 检测输入的是否为 url
        ,checkEmptyOrUrl: function(value)
        {
            if(value.trim().length > 0 && !/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/.test(value)) return "链接格式不正确";
        }
        // 检测输入的是否为 email
        ,checkEmptyOrEmail: function(value)
        {
            if(value.trim().length > 0 && !/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) return "邮箱格式不正确";
        }
        // 检测输入的是否为 手机
        ,checkEmptyOrPhone: function(value)
        {
            if(value.trim().length > 0 && !/(^$)|^1\d{10}$/.test(value)) return "请输入正确的手机号";
        }
        // 检测输入的是否为 日期
        ,checkEmptyOrDate: function(value)
        {
            if(value.trim().length > 0 && !/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/.test(value)) return "日期格式不正确";
        }
        // 检测输入的是否为 身份证
        ,checkEmptyOrIdentity: function(value)
        {
            if(value.trim().length > 0 && !/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/.test(value)) return "请输入正确的身份证号";
        }
    };
    form.verify({
        emptyNumber: validate.checkEmptyOrNumber
        ,emptyUrl: validate.checkEmptyOrUrl
        ,emptyEmail: validate.checkEmptyOrEmail
        ,emptyPhone: validate.checkEmptyOrPhone
        ,emptyDate: validate.checkEmptyOrDate
        ,emptyIdentity: validate.checkEmptyOrIdentity
    });

    exports('longli', longli);
});